/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.h2o3.server.launcher;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.google.common.base.Objects;

/**
 * @author chensheng
 * @version $Id: LauncherServlet.java, v 0.1 11/30/13 1:29 PM chensheng Exp $
 */
public class Launcher {
    public static void main(String[] args) throws IOException {
        new Launcher().launch();
    }

    public void launch() throws IOException {
        loadConfig();

        new ClassPathXmlApplicationContext(
            new String[] { "META-INF/spring/applicationContext.xml" }).start();

        serverConsole();
    }

    private void serverConsole() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out));

        while (true) {
            writer.write("> ");
            writer.flush();

            String line = reader.readLine();
            if (Objects.equal("exit", line)) {
                break;
            }
        }
    }

    private void loadConfig() throws IOException {
        Properties properties = new Properties();

        InputStream propertiesInputStream = Launcher.class.getResourceAsStream("/db.properties");
        if (propertiesInputStream != null) {
            properties.load(propertiesInputStream);
        } else {
            properties.load(new FileInputStream("etc/db.properties"));
        }

        System.getProperties().putAll(properties);
    }
}
